
'use strict';
/*!
 * RTColorPicker Polyfill
 * Provides a lightweight color picker interface compatible with RTColorPicker.create({ initial, onChange })
 * It uses a hidden <input type="color"> and calls onChange(hex) on input/change events.
 * It also renders a "最近使用" (Recently used) swatch row inside #tp-colorboard controls.
 */
(function(window, document){
  if(window.RTColorPicker && typeof window.RTColorPicker.create === 'function'){
    // Already present (real implementation). Still enhance with "recent" feature.
  }

  const LS_KEY = 'rt_recent_colors';
  const MAX_RECENT = 8;

  function loadRecent(){
    try{
      const arr = JSON.parse(localStorage.getItem(LS_KEY) || '[]');
      if(Array.isArray(arr)) return arr.filter(x=>/^#[0-9a-fA-F]{6}$/.test(x)).slice(0, MAX_RECENT);
    }catch(e){}
    return [];
  }
  function saveRecent(list){
    try{ localStorage.setItem(LS_KEY, JSON.stringify(list.slice(0, MAX_RECENT))); }catch(e){}
  }
  function pushRecent(hex){
    const h = (hex||'').toUpperCase();
    if(!/^#[0-9A-F]{6}$/.test(h)) return;
    const list = loadRecent().filter(x=>x !== h);
    list.unshift(h);
    saveRecent(list);
    renderRecent(); // update UI immediately
  }

  // Render "最近使用" UI inside #tp-colorboard .cb-controls (or fallbacks)
  function renderRecent(){
    const board = document.querySelector('#tp-colorboard');
    if(!board) return;
    const host = board.querySelector('.cb-controls') || board.querySelector('.cb-left') || board;
    let wrap = board.querySelector('#rt-recent-wrap');
    if(!wrap){
      wrap = document.createElement('div');
      wrap.id = 'rt-recent-wrap';
      wrap.className = 'rt-recent';
      wrap.setAttribute('role','group');
      wrap.setAttribute('aria-label','最近使用的颜色');
      // label
      const label = document.createElement('span');
      label.className = 'rt-recent__label';
      label.textContent = '最近使用';
      // list
      const listEl = document.createElement('div');
      listEl.className = 'rt-recent__list';
      wrap.appendChild(label);
      wrap.appendChild(listEl);
      // Put it near the controls area
      host.appendChild(wrap);
    }
    const listEl = wrap.querySelector('.rt-recent__list');
    listEl.innerHTML = '';
    const items = loadRecent();
    if(items.length === 0){
      const hint = document.createElement('span');
      hint.className = 'rt-recent__hint';
      hint.textContent = '（空）';
      listEl.appendChild(hint);
      return;
    }
    // Create swatches
    items.forEach(hex=>{
      const btn = document.createElement('button');
      btn.type = 'button';
      btn.className = 'rt-recent__swatch';
      btn.title = hex;
      btn.setAttribute('data-hex', hex);
      btn.style.background = hex;
      btn.addEventListener('click', function(e){
        try{
          // Reuse the same selection flow as palette dots (fake dot technique)
          const grid = document.querySelector('#tp-colorboard .cb-grid');
          if(grid){
            let fake = grid.querySelector('.dot#rt-temp-dot');
            if(!fake){
              fake = document.createElement('button');
              fake.id = 'rt-temp-dot';
              fake.className = 'dot';
              fake.style.position = 'absolute';
              fake.style.width = '0';
              fake.style.height = '0';
              fake.style.padding = '0';
              fake.style.margin = '0';
              fake.style.border = '0';
              fake.style.overflow = 'hidden';
              fake.style.left = '-9999px';
              grid.appendChild(fake);
            }
            fake.setAttribute('data-hex', hex);
            fake.style.background = hex;
            fake.click();
          }
          // Also reflect to the "已选颜色" text if present
          const sel = document.getElementById('tp-selected');
          if(sel) sel.textContent = hex.toUpperCase();
          if(typeof window.__syncSelectedColor === 'function'){ window.__syncSelectedColor(hex.toUpperCase()); }
        }catch(err){}
      });
      listEl.appendChild(btn);
    });
  }

  // Minimal picker implementation
  function create(opts){
    const opt = Object.assign({ initial: '#27E6B8', onChange: function(){} }, opts||{});
    let input = null;
    function ensure(){
      if(input) return input;
      input = document.createElement('input');
      input.type = 'color';
      input.id = 'rt-hidden-color-input';
      input.style.position = 'fixed';
      input.style.left = '-9999px';
      input.style.top = '0';
      input.style.width = '1px';
      input.style.height = '1px';
      input.style.opacity = '0';
      document.body.appendChild(input);
      input.addEventListener('input', function(){
        try{
          const v = input.value || '';
          if(/^#[0-9a-fA-F]{3,6}$/.test(v)){
            const hex = normalizeHex(v);
            opt.onChange(hex);
            pushRecent(hex);
          }
        }catch(e){}
      });
      input.addEventListener('change', function(){
        try{
          const v = input.value || '';
          if(/^#[0-9a-fA-F]{3,6}$/.test(v)){
            const hex = normalizeHex(v);
            opt.onChange(hex);
            pushRecent(hex);
          }
        }catch(e){}
      });
      return input;
    }
    function normalizeHex(h){
      let v = (h||'').trim();
      if(/^#[0-9a-f]{3}$/i.test(v)){ // expand #abc to #aabbcc
        v = '#'+v.slice(1).split('').map(ch=>ch+ch).join('');
      }
      v = v.toUpperCase();
      if(!/^#[0-9A-F]{6}$/.test(v)){ return '#27E6B8'; }
      return v;
    }
    return {
      open: function(anchor){
        const el = ensure();
        // Set initial value
        try{
          el.value = normalizeHex(opt.initial||'#27E6B8');
        }catch(e){}
        // Programmatically open native picker
        try{ el.click(); }catch(e){}
      }
    };
  }

  // expose
  window.RTColorPicker = window.RTColorPicker || { create: create };
  // expose a push(hex) API for external callers to record a color into recent
  window.RTColorPicker.push = function(hex){ try{ if(hex && typeof hex==='string'){ var h = hex.trim(); if(h && h[0]!=='#' && /^[0-9A-Fa-f]{6}$/.test(h)) h='#'+h; pushRecent(h); } }catch(e){} };

  // Auto-render "recent" when the colorboard appears
  function when(condFn, cb){
    if (condFn()) return cb();
    var mo = new MutationObserver(()=>{ if (condFn()){ mo.disconnect(); cb(); } });
    mo.observe(document.documentElement, {childList:true, subtree:true});
  }
  when(()=> !!document.querySelector('#tp-colorboard'), renderRecent);
})(window, document);
